import 'package:flutter/material.dart';
import 'package:flutter_shop/cons/global_cons.dart';
import 'package:flutter_shop/pages/common/login/entity/user_info.dart';
import 'package:flutter_shop/pages/common/login/provider/login_provider.dart';
import 'package:flutter_shop/utils/sp_util.dart';
import 'package:flutter_shop/utils/utils.dart';
import 'package:provider/provider.dart';

/// Title:基本信息 <br/>
/// Description: <br/>
/// author:xiemiao <br/>
/// date: 2020-03-12  <br/>
/// version 1.0 <br/>
class BaseInfo {
  static String _token;
  static UserInfo _userInfo;

  ///设置token
  static void setToken(String token) {
    _token = token;
    SpUtil.putString(GlobalCons.KEY_TOKEN, _token);
  }

  ///获取token
  static String getToken() {
    if (Utils.strIsEmpty(_token)) {
      _token = SpUtil.getString(GlobalCons.KEY_TOKEN, defValue: "");
    }
    return _token;
  }

  /// 设置用户信息
  static void setUserInfo(BuildContext context, UserInfo userInfo) {
    _userInfo = userInfo;
    SpUtil.putObject(GlobalCons.KEY_USER, _userInfo);
    if (context != null) {
      Provider.of<LoginProvider>(context, listen: false).setUserInfo(getUserInfo());
    }
  }

  /// 获取用户信息
  static UserInfo getUserInfo() {
    if (_userInfo == null) {
      _userInfo = SpUtil.getObj(GlobalCons.KEY_USER, (v) => UserInfo().fromJson(v));
    }
    return _userInfo;
  }

  /// 清除用户信息
  static void clearUserInfo(BuildContext context) {
    _token = null;
    _userInfo = null;
    SpUtil.remove(GlobalCons.KEY_TOKEN);
    SpUtil.remove(GlobalCons.KEY_USER);

    //清除状态管理用户信息
    Provider.of<LoginProvider>(context, listen: false).clearUserInfo();
  }

  ///恢复用户信息到状态管理
  static void restoreUserInfo(BuildContext context) {
    Provider.of<LoginProvider>(context, listen: false).setUserInfo(getUserInfo());
  }

  /// 判断用户是否登录
  static bool isLogin() {
    return Utils.strIsNotEmpty(getToken()) && getUserInfo() != null;
  }
}
